package com.br.command.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.br.command.BaseCommand;
import com.br.socket.ConnectionWS;
import com.br.socket.GameSocket;
import com.br.utils.BufferUtils;

public class Desconectar implements BaseCommand{
	
	private Logger logger = Logger.getLogger(this.getClass());

	public void process(ConnectionWS me, JSONObject json) {
		
		//verificar e desconectar outro player caso esteja na conta
		List<ConnectionWS> connections = GameSocket.getConnections();
		synchronized (connections) {
			for (int i = 0; i < connections.size(); i++) {
				try {
					ConnectionWS con = connections.get(i);
					
					if(con.getId().equals(me.getId())){
						logger.debug("Desconectando player da conta...");
						connections.remove(i);
						//notifica os outros player para removelo da tela
						GameSocket.broadcast(BufferUtils.desconectarOtherPlayer(me.getPlayer().getUsername()).toString(), me);
					}
				
				} catch (Exception e) {
					logger.error("Erro em Desconectar",e);
				}
				
			}
		}
		
	}

}
